// 简单的日志工具
const fs = require('fs');
const path = require('path');

class Logger {
  constructor() {
    this.logDir = path.join(__dirname, '../../logs');
    this.ensureLogDir();
  }

  ensureLogDir() {
    if (!fs.existsSync(this.logDir)) {
      fs.mkdirSync(this.logDir, { recursive: true });
    }
  }

  getTimestamp() {
    return new Date().toISOString();
  }

  getLogFileName() {
    const date = new Date().toISOString().split('T')[0];
    return path.join(this.logDir, `app-${date}.log`);
  }

  formatMessage(level, message, data = null) {
    const timestamp = this.getTimestamp();
    let logMessage = `[${timestamp}] [${level}] ${message}`;
    if (data) {
      logMessage += ` ${JSON.stringify(data)}`;
    }
    return logMessage;
  }

  writeToFile(message) {
    try {
      const logFile = this.getLogFileName();
      fs.appendFileSync(logFile, message + '\n', 'utf8');
    } catch (error) {
      console.error('写入日志文件失败:', error);
    }
  }

  info(message, data = null) {
    const logMessage = this.formatMessage('INFO', message, data);
    console.log('ℹ️ ', message, data || '');
    this.writeToFile(logMessage);
  }

  error(message, data = null) {
    const logMessage = this.formatMessage('ERROR', message, data);
    console.error('❌', message, data || '');
    this.writeToFile(logMessage);
  }

  warn(message, data = null) {
    const logMessage = this.formatMessage('WARN', message, data);
    console.warn('⚠️ ', message, data || '');
    this.writeToFile(logMessage);
  }

  success(message, data = null) {
    const logMessage = this.formatMessage('SUCCESS', message, data);
    console.log('✅', message, data || '');
    this.writeToFile(logMessage);
  }

  pay(message, data = null) {
    const logMessage = this.formatMessage('PAY', message, data);
    console.log('💰', message, data || '');
    this.writeToFile(logMessage);
    
    // 支付相关日志额外记录到专门的文件
    try {
      const date = new Date().toISOString().split('T')[0];
      const payLogFile = path.join(this.logDir, `pay-${date}.log`);
      fs.appendFileSync(payLogFile, logMessage + '\n', 'utf8');
    } catch (error) {
      console.error('写入支付日志失败:', error);
    }
  }
}

module.exports = new Logger();

